#!/usr/bin/env bash
# The purpose of this script is to release the current version by creating and pushing a tag

REMOTE='origin'

# Ensure that the script is being run from the root project directory
PROPERTIES_FILE='gradle.properties'
if [ ! -f "$PROPERTIES_FILE" ]; then
  echo "Could not find $PROPERTIES_FILE, please run this script from the root project directory."
  exit 2
fi

# Process CLI arguments
TARGET="HEAD"
for ARG in "$@"; do
  if [ "$ARG" = '-h' ] || [ "$ARG" = '--help' ]; then
    cat ./scripts/help-text/release.txt
    exit 0
  else
    TARGET="$1"
  fi
done

# Determine and verify the target commit
TARGET_COMMIT=`git rev-parse --verify $TARGET`
if [ $? != 0 ]; then
  echo "Invalid target: $TARGET"
  echo ''
  cat ./scripts/help-text/release.txt
  exit 2
fi

# Ensure that the target commit is an ancestor of master
git merge-base --is-ancestor $TARGET_COMMIT master
if [ $? != 0 ]; then
  echo "Invalid target: $TARGET"
  echo 'Please select a target commit which is an ancestor of master.'
  exit 1
fi

# Determine version to be released
VERSION=`awk 'BEGIN { FS = "=" }; $1 == "version" { print $2 }' $PROPERTIES_FILE | awk '{ print $1 }'`
if [ -z "$VERSION" ]; then
  echo "Could not read the version from $PROPERTIES_FILE, please fix it and try again."
  exit 1
fi

# Ensure that release tag name wouldn't conflict with a local branch
TAG_NAME="v$VERSION"
git show-ref --verify refs/heads/$TAG_NAME >/dev/null 2>&1
if [ $? = 0 ]; then
  echo "Cannot create tag $TAG_NAME, as it would conflict with a local branch of the same name."
  echo 'Please delete this branch and avoid naming branches like this in the future.'
  echo "Hint: 'git branch -D $TAG_NAME' (WARNING: you will lose all local changes on this branch)"
  exit 1
fi

# Create release tag
git tag -a $TAG_NAME $TARGET_COMMIT -m "$TAG_NAME"
if [ $? != 0 ]; then
  echo "Could not create tag $TAG_NAME"
  exit 1
else
  echo "Created tag $TAG_NAME at commit $TARGET_COMMIT ($TARGET)"
fi

# Push release tag
echo "Pushing tag $TAG_NAME..."
git push $REMOTE $TAG_NAME

if [ $? != 0 ]; then
  echo 'Push failed, clearing tag from local repo...'
  git tag -d $TAG_NAME
  exit 1
fi

echo "Tag push complete. You can view the $TAG_NAME publish job here: https://github.com/linkedin/parseq/actions/workflows/publish.yml"
